<template>
  <div class="modifybox">
    <el-collapse accordion v-model="activeNames">
      <el-collapse-item name="course-info">
        <template class="courseheaderbox" slot="title">
          <div class="courseheaderbox course-header">
            <i class="courseico header-icon el-icon-arrow-down"></i>
            <span class="corsespan">{{xsname}} </span>
            <i class="courseico header-icon el-icon-edit"></i>
          </div>
        </template>
        <div class="tinymce-container">
          <el-form ref="form">   
            <el-form-item label="课程标题"  label-width="100px">
              <el-input v-model="course.courseName"></el-input>
            </el-form-item>
            <el-form-item label="课程描述"  label-width="100px">
              <el-input v-model="course.description" type="textarea" rows="10"></el-input>
            </el-form-item>
            <el-form-item label="课程标签"  label-width="100px">
              <el-input v-model="course.keyword"></el-input>
            </el-form-item>

            <el-form-item label="课程分类" label-width="100px">
              <el-select v-model="course.typeId" placeholder="请选择课程分类">
                <el-option
                      v-for="item in sourcetype_list"
                      :key="item.id"
                      :label="item.typeName"
                      :value="item.id"
                    ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="封面"  label-width="100px">
              <div class="single_pic" @click="selectSinglePic">
                <svg class="icon svg-icon" aria-hidden="true">
                  <use xlink:href="#icon_btn_addpic" />
                </svg>
                <span>选择图片</span>
                <img v-if="course.image" :src="course.image" />
              </div>
            </el-form-item>
            <el-form-item class="btn">
              <el-button type="success" class="filter-item" @click="modifyCourseInfo()">
                <svg class="icon svg-icon" aria-hidden="true">
                  <use xlink:href="#iconicon_btn_tjsh" />
                </svg>
                保存课程
              </el-button>
            </el-form-item>
          </el-form>
          <el-dialog
            width="849px"
            :visible.sync="showPicDialog"
            :close-on-click-modal="false"
            :show-close="false"
            :center="true"
          >
            <!-- 本地上传 -->
            <div>
              <upload :imgChange="uploadSuccess" />
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="warning" @click="cancleImg">取 消</el-button>
              <el-button type="success" @click="btnOKImg">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-collapse-item>

      <el-collapse-item name="course-nodes">
        <template slot="title">
          <div class="courseheaderbox course-header">
              <i class="courseico header-icon el-icon-arrow-down"></i>
              <span class="corsespan">章节列表</span>
              <el-button @click.stop="addNodeWindow()" type="success" icon="el-icon-plus">添加章节</el-button>
            </div>
        </template>
        <div class="nodebox">
          <template>
            <el-table
              :data="courseNodes"
              row-key="id"
              style="width: 100%">
              <el-table-column
                label="索引"
                type="index"
                width="50">
              </el-table-column>
              <el-table-column
                prop="nodeName"
                label="章节名称"
                width="200">
              </el-table-column>
              <el-table-column
                prop="keywords"
                label="章节标签"
                width="180">
              </el-table-column>
              <el-table-column
                prop="description"
                label="章节描述">
              </el-table-column>
              <el-table-column
                prop="viewCount"
                label="浏览"
                width="100">
              </el-table-column>
              <el-table-column
                prop="collectCount"
                label="收藏"
                width="100">
              </el-table-column>
              <el-table-column
                prop="commentCount"
                label="评论"
                width="100">
              </el-table-column>
               <el-table-column
                label="操作"
                align="center"
                width="150">
                <template slot-scope="scope">
                  <i class="move-icon el-icon-rank"></i>
                  <el-button type="text" @click="modifyNodeWindow(scope.row)" size="small">编辑</el-button>
                  <el-button type="text" @click="delCourseNode(scope.row)" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 编辑课程章节 -->
    <el-drawer
      class="coursenodedrawer"
      :title="wdtitle"
      :size="size"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose">
      <NodeBox ref="nodewindow" :courseNodeData="courseNode" :saveCourseNodeInfo="nodeSave"></NodeBox>
    </el-drawer>
  </div>
</template>

<script>
import Upload from '@/components/Upload/upload.vue'
import NodeBox from './components/NodeBox1.vue'
// draggable 依赖于 Sortable，当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable"
import Sortable from "sortablejs"
import {sortCourseNode,getSourceTypes,modifyCourse,oneCourse,addCourseNode,modifyCourseNode,oneCourseNode,allCourseNode,deleteCourseNode} from '@/api/publish'
export default {
  name: 'PublishCourse',
  components: { Upload,NodeBox,draggable,Sortable },
  data () {
    return {
      activeNames:'course-nodes',
      size:'100%',
      drawer: false,
      direction: 'rtl',
      wdtitle:'', //窗口标题
      singlePic: null, // 单图模式
      sourcetype_list: [],
      selectedImg:'',
      course:{
        typeName:'',//分类名字
        typeId:'',//分类ID
        courseName:'',//课程名字
        image:'',//课程图片
        keyword:'',//标签、关键词
        description:'',//描述
        id:'' //ID
      },
      //章节内容
      courseNode:{
        nodeName:'',//章节名称
        content:'',//章节内容
        description:'',//章节描述
        keywords:'',//章节关键词
        courseId:'', //所属课程ID
        id:'',
        sourceId:'',
        status:0   //0：发布  1：保存为草稿
      },
      courseNodes:[], //章节列表
      //章节列表
      showPicDialog:false,//弹层
      xsname:'',   //展示的名字
    }
  },
  beforeMount () {
    this.courseLoad()
  },
  created() {
    //拖拽功能
    this.$nextTick(() => {
      this.courseNodeList();
    });
  },
  methods: {
    //加载数据
    courseLoad(){
      this.oneCourseDetail()
      this.getSourceType() // 拉取分类列表
      //this.courseNodeList()
    },
    //添加章节内容
    async addNodeWindow(){
      this.drawer=true
      //初始化参数 nodewindow
      if(this.$refs['nodewindow']){
        this.$refs['nodewindow'].initCourseNodData()
      }
      this.wdtitle=this.course.courseName+'》添加新章节'
    },

    //删除
    async delCourseNode(row){
       this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let id = row.id
          const result = deleteCourseNode(id)
          this.$message({ type: 'success', message: '删除章节成功' })
          //刷新
          this.courseNodes.splice(this.courseNodes.indexOf(row),1)
        })
    },

    //修改章节内容
    async modifyNodeWindow(row){
      this.drawer=true
      this.wdtitle=this.course.courseName+'》修改新章节'
      //设置数据
      this.$nextTick(() => {
        this.$refs['nodewindow'].loadCourseNodData(row)
      })
    },

    //内容保存
    nodeSave(courseNodeInfo){
      //增加
      this.courseNode=JSON.parse(JSON.stringify(courseNodeInfo))
      this.courseNode.courseId=this.course.id
      this.courseNode.sourceId=this.course.typeId
      console.log(this.courseNode)
      //保存或者添加文章章节
      this.saveCourseNode()
    },

    //添加、修改章节
    async saveCourseNode(){
      let result = null
      if(this.courseNode.id==undefined || this.courseNode.id==null || this.courseNode.id==''){
        result = await addCourseNode(this.courseNode)
      }else{
        result = await modifyCourseNode(this.courseNode)
      }
      if (result.code === 20000) {
        this.$message({ type: 'success', message: '章节操作成功' })
        //关闭弹窗
        this.drawer=false
        //重新加载数据
        this.courseLoad()
      } else {
        this.$message({ type: 'error', message: result.message })
      }
    },

    //查询所有
    async courseNodeList(){
      //获取课程ID
      const id = this.$route.query.id
      const result = await allCourseNode(id)
      this.courseNodes = result.data

      const el = document.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: 'sortable-ghost', //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        onEnd: (e) => { // 拖拽结束时的触发
            let arr = this.courseNodes; // 获取表数据
            arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理，获取最新的表格数据
            this.$nextTick(function () {
              this.courseNodes= arr;
              let ids = this.courseNodes.map(item => {
                return item.id;
              })
              //调用后台修改排序 
              sortCourseNode(ids)
            })
        },
      });
    },

    //关闭编辑窗口
    handleClose(done) {
        this.$confirm('尚未保存，是否确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
    //获取课程详情
    async oneCourseDetail(){
      //获取课程ID
      const id = this.$route.query.id
      //执行根据ID查询
      const result = await oneCourse(id)
      this.course=result.data
      //展示名字
      this.xsname = this.course.courseName
    },

    // 获取课程分类集合
    async getSourceType () {
      const result = await getSourceTypes()
      this.sourcetype_list = result.data
    },

    //获取指定id的分类
    oneSourceType(id){
      for(var i=0;i<this.sourcetype_list.length;i++){
        let courseType = this.sourcetype_list[i]
        if(courseType.id==id){
          return courseType
        }
      }
    },

    //保存课程
    async modifyCourseInfo () {
      let courseType = this.oneSourceType(this.course.typeId)
      this.course.typeName=courseType.typeName
      const result = await modifyCourse(this.course)
      if (result.code === 20000) {
          // 写多了if  else 写个三元表达式 换换口味
          this.$message({ type: 'success', message: '修改成功' })
        } else {
          this.$message({ type: 'error', message: result.message })
        }
    },
    // 上传成功后
    uploadSuccess (url) {
      this.selectedImg =  url  // 将上传的图片认为是新组件
    },
    // 选择单张图片
    selectSinglePic () {
      this.showPicDialog = true // 显示弹层
    },
    // 取消插入图片
    cancleImg () {
      this.showPicDialog = false // 关闭弹层
    },
    // 插入图片 或者替换封面图片
    btnOKImg () {
      this.course.image=this.selectedImg //图片替换
      this.selectedImg = '' // 首先清空选择的缓存
      this.showPicDialog = false // 关闭弹层
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/scss/element-variables.scss';
.tinymce-container {
  padding: 30px;
  text-align: left;

  .el-form {
    .title {
      .el-input__inner {
        padding: 0;
        padding-bottom: 19px;
        border: none;
        border-bottom: 2px solid #ebeef5;
        border-radius: 0;
        line-height: 26px;
        font-size: 20px;
        color: $--color-text-placeholder;
      }
    }

    // .el-form-item {
    //   margin: 20px 0;
    // }

    .btn {
      border-top: 2px solid #ebeef5;
      // margin: 0 15px;
      // padding: 30px 0;
      padding-top: 31px;
      margin-bottom: 0;
    }
  }
}

.editor-content {
  margin-top: 20px;
}

.img_list {
  width: 155px;
  height: 103px;
  float: left;
  margin: 0px auto;
  border: 1px solid #eee;
  overflow: hidden;
  border-radius: 4px;
  margin: 0px 18px 16px 0;
  position: relative;
}

.img_list_con {
  flex: 1;
  overflow: hidden;
  margin-left: 30px;
  max-height: 340px;
}

.selected {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 32px !important;
  height: 33px !important;
}

.img_list img {
  width: 155px;
  height: 103px;
  display: block;
  cursor: pointer;
}

.pagination {
  text-align: center;
}

.upload_pic_show {
  display: block;
  width: 240px;
  height: 180px;
  margin: 15px auto 10px;
}

.single_pic {
  width: 278px;
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed $--border-color-base;
  border-radius: 4px;
  cursor: pointer;
}

.three_pic {
  display: flex;
  flex-direction: row;
  width: 840px;
  height: 180px;
  cursor: pointer;

  .three_pic_item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed $--border-color-base;
    border-right: none;
  }

  .three_pic_item:last-child {
    border-right: 2px dashed $--border-color-base;
  }
}

.single_pic:hover, .three_pic_item:hover {
  color: $--color-primary;
}

.single_pic .icon, .three_pic .three_pic_item .icon {
  width: 40px;
  height: 40px;
}

.single_pic span, .three_pic .three_pic_item span {
  line-height: normal;
}

.single_pic img, .three_pic .three_pic_item img {
  width: 278px;
  height: 180px;
  object-fit: cover;
}

.el-switch {
  height: auto;
  margin-bottom: 30px;
}

.el-switch__label {
  position: absolute;
  color: $--color-text-secondary;
}

.el-switch__label.is-active {
  color: $--color-text-primary;
  font-weight: 600;
}

.el-switch__label--left {
  left: 0;
  margin-left: 16px;
  z-index: 9999;
}

.el-switch__label--right {
  right: 0;
  margin-right: 10px;
}

.el-switch__core {
  height: 40px;
  border-radius: 4px;
}

.el-switch__core:after {
  width: 66px;
  height: 32px;
  top: 3px;
  left: 3px;
  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
}

.el-switch.is-checked .el-switch__core::after {
  margin-left: 76px;
  left: 3px;
}

.el-dialog__footer {
  border-top: 2px solid #EBEEF5;
}
.el-select{
  width: 100%;
}
.corsespan{
  padding-left: 60px;
  padding-right: 50px;
}
.course-header{
  font-size: 18px;
  font-weight: 500;
}
.courseheaderbox{
  background: #DFE0E6;
  width: 100%;
}
.courseico{
  padding-left: 15px;
}
.nodebox{
  padding-left: 60px;
}
</style>
